package com.childenglish.validation;

import com.childenglish.utils.DataEncryptionUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.lang.reflect.Field;

/**
 * 密码匹配验证器
 */
public class PasswordMatchValidator implements ConstraintValidator<PasswordMatch, Object> {
    
    private String passwordField;
    private String confirmPasswordField;
    
    @Override
    public void initialize(PasswordMatch constraintAnnotation) {
        this.passwordField = constraintAnnotation.password();
        this.confirmPasswordField = constraintAnnotation.confirmPassword();
    }
    
    @Override
    public boolean isValid(Object obj, ConstraintValidatorContext context) {
        if (obj == null) {
            return true;
        }
        
        try {
            Field passwordFieldObj = obj.getClass().getDeclaredField(passwordField);
            Field confirmPasswordFieldObj = obj.getClass().getDeclaredField(confirmPasswordField);
            
            passwordFieldObj.setAccessible(true);
            confirmPasswordFieldObj.setAccessible(true);
            
            Object passwordValue = passwordFieldObj.get(obj);
            Object confirmPasswordValue = confirmPasswordFieldObj.get(obj);
            
            if (passwordValue == null && confirmPasswordValue == null) {
                return true;
            }
            
            if (passwordValue == null || confirmPasswordValue == null) {
                return false;
            }
            
            String password = passwordValue.toString();
            String confirmPassword = confirmPasswordValue.toString();
            
            // 如果密码是加密的，尝试解密后再比较
            try {
                password = DataEncryptionUtils.decrypt(password);
            } catch (Exception e) {
                // 如果解密失败，说明是明文，直接使用
            }
            
            try {
                confirmPassword = DataEncryptionUtils.decrypt(confirmPassword);
            } catch (Exception e) {
                // 如果解密失败，说明是明文，直接使用
            }
            
            return password.equals(confirmPassword);
        } catch (Exception e) {
            return false;
        }
    }
}

